package me.tuyou.es.java.service;

import me.tuyou.es.java.dto.Hotel;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EsService {

    @Autowired
    RestHighLevelClient client;

    public List<Hotel> getHotelFromTitle(String keyword) {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("title", keyword));
        request.source(searchSourceBuilder);

        List<Hotel> resultList = new ArrayList<>();
        try {
            SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
            RestStatus status = searchResponse.status();
            if (status != RestStatus.OK) {
                return null;
            }

            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                Hotel hotel = new Hotel();
                hotel.setId(hit.getId());
                hotel.setIndex(hit.getIndex());
                hotel.setScore(hit.getScore());

                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                hotel.setTitle((String) sourceAsMap.get("title"));
                hotel.setCity((String) sourceAsMap.get("city"));
                hotel.setPrice((Double) sourceAsMap.get("price"));
                resultList.add(hotel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    public void singleIndexDoc(Map<String, Object> dataMap, String indexName, String indexId) throws IOException {
        IndexRequest indexRequest = new IndexRequest(indexName).id(indexId).source(dataMap);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        String index = response.getIndex();
        String id = response.getId();
        long version = response.getVersion();
        System.out.println("index=" + index + ",id=" + id + ",version=" + version);
    }
}
